<?php
error_reporting(E_ALL);
ini_set('display_errors', 0);
header('Content-Type: application/json');

// 日志记录函数已禁用
// function writeLog($message) {}

try {
    // writeLog('MySQL配置保存请求开始');
    
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        // writeLog('错误: 请求方法不正确');
        echo json_encode(['success' => false, 'message' => '请求方法错误']);
        exit;
    }

    $enabled = isset($_POST['enabled']) && $_POST['enabled'] === 'true' ? true : false;
    $secret_id = $_POST['secret_id'] ?? '';
    $secret_key = $_POST['secret_key'] ?? '';
    $region = $_POST['region'] ?? 'ap-guangzhou';
    $instance_id = $_POST['instance_id'] ?? '';
    $host = $_POST['host'] ?? '';
    $port = $_POST['port'] ?? '3306';
    $database = $_POST['database'] ?? '';
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';

    // 日志已禁用
    // writeLog("配置参数 - Enabled: " . ($enabled ? 'true' : 'false') . ", Region: {$region}, Instance ID: {$instance_id}, Host: {$host}, Port: {$port}, Database: {$database}, Username: {$username}");

    if (empty($secret_id) || empty($secret_key)) {
        // writeLog('错误: 缺少API密钥信息');
        echo json_encode(['success' => false, 'message' => '缺少API密钥信息']);
        exit;
    }

    $configFile = __DIR__ . '/../../config.php';

    if (!file_exists($configFile)) {
        // writeLog('错误: 配置文件不存在');
        echo json_encode(['success' => false, 'message' => '配置文件不存在']);
        exit;
    }

    // writeLog('读取现有配置文件');
    $configContent = file_get_contents($configFile);

    $newMysqlConfig = sprintf(
        "'mysql' => [\n            'enabled' => %s,\n            'secret_id' => '%s',\n            'secret_key' => '%s',\n            'region' => '%s',\n            'instance_id' => '%s',\n            'host' => '%s',\n            'port' => '%s',\n            'database' => '%s',\n            'username' => '%s',\n            'password' => '%s'\n        ]",
        $enabled ? 'true' : 'false',
        addslashes($secret_id),
        addslashes($secret_key),
        addslashes($region),
        addslashes($instance_id),
        addslashes($host),
        addslashes($port),
        addslashes($database),
        addslashes($username),
        addslashes($password)
    );

    $pattern = "/'mysql' => \[(?:[^\[\]]*|\[[^\]]*\])*\]/s";
    $configContent = preg_replace($pattern, $newMysqlConfig, $configContent);

    // writeLog('尝试保存配置到文件');
    if (file_put_contents($configFile, $configContent)) {
        // writeLog('配置保存成功');
        echo json_encode(['success' => true, 'message' => '配置保存成功']);
    } else {
        // writeLog('错误: 配置保存失败');
        echo json_encode(['success' => false, 'message' => '配置保存失败']);
    }
} catch (Exception $e) {
    $errorMsg = $e->getMessage();
    // writeLog("系统错误: {$errorMsg}");
    echo json_encode(['success' => false, 'message' => '系统错误: ' . $errorMsg]);
}
exit;
